package testJDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-05-15
 * Time: 20:18
 */
public class Demo03_Insert {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        //插入操作不需要定义结果集对象 因为insert返回的时受影响的行数

        try {
            //1.获取数据库的连接
            connection = DButil.getConnection();
            //2.定义sql
            String sql = "insert into student (sn, name, mail, class_id) values (?, ?, ?, ?)";
            //3.定义sql预处理对象
            preparedStatement = connection.prepareStatement(sql);
            //4.接受用户参数
            System.out.println("请输入学号：");
            Scanner scanner = new Scanner(System.in);
            String sn = scanner.next();

            System.out.println("请输入姓名：");
            String name = scanner.next();

            System.out.println("请输入邮箱：");
            String mail = scanner.next();

            System.out.println("请输入班级编号：");
            Long class_id = Long.valueOf(scanner.next());

            //5.用真实数据填充占位符
            preparedStatement.setString(1, sn);
            preparedStatement.setString(2, name);
            preparedStatement.setString(3, mail);
            preparedStatement.setLong(4, class_id);

            //6.执行sql获取结果
            int row = preparedStatement.executeUpdate();

            //7.判断结果
            if (row == 1) {
                System.out.println("插入成功");
            }else {
                System.out.println("插入失败");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(null, preparedStatement, connection);
        }
    }
}
